package com.tkjy.service.impl;

import com.tkjy.mapper.AccountMapper;
import com.tkjy.pojo.Account;
import com.tkjy.pojo.PageTransaction;
import com.tkjy.pojo.Transaction;
import com.tkjy.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.DataTruncation;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

@Service
public class AccountServiceImpl implements AccountService {
    @Autowired
    private AccountMapper accountMapper;

    @Override
    public Account selectAccount(Account account) {
        return accountMapper.selectAccount(account);
    }

    @Override
    public boolean updatePassword(String password, String cardno) {
        return accountMapper.updatePassword(password, cardno) > 0;
    }


    @Override
    public PageTransaction selectTransaction(String firstDate, String lastDate, String cardno, Integer pageNo, Integer pageSize) {
        PageTransaction page = new PageTransaction();
        int count = accountMapper.count(firstDate, lastDate, cardno);
        page.setPageSize(pageSize);
        page.setTotal(count);
        List<Transaction> list = accountMapper.selectTransaction(firstDate, lastDate, cardno, page.offset(), page.getPageSize());
        page.setList(list);
        return page;
    }

    @Transactional
    @Override
    public Boolean updateMoney(Double money, String carDno, String newCarDno) {
        Account a1 = accountMapper.selectCarDno(carDno);
        Account a2 = accountMapper.selectCarDno(newCarDno);
        if(a2==null){
            return false;
        }
        a1.setBalance(a1.getBalance() - money);
        int i3 = accountMapper.updateCarDno(a1);
        a2.setBalance(a2.getBalance() + money);
        int i4 = accountMapper.updateCarDno(a2);
        Transaction t1 = new Transaction(a1.getCardno(), -money, a1.getBalance(), "转账");
        int i2 = accountMapper.insertTransaction(t1);
        Transaction t2 = new Transaction(a2.getCardno(), money, a2.getBalance(), "转账");
        int i = accountMapper.insertTransaction(t2);
        return i>0 && i2>0 && i3 > 0 && i4 > 0;
    }
}
